﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Data;
using System.ComponentModel;
using VSA.Applications.VSA.WebService;

namespace VSA.Applications
{
    public class Utility
    {
        [DllImport("shell32.dll", EntryPoint = "ShellExecuteA")]
        public static extern int ShellExecute(
         int hwnd,
         String lpOperation,
         String lpFile,
         String lpParameters,
         String lpDirectory,
         int nShowCmd
         );


        public static void DisplayResult(Label label, string message, AsyncCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                safeSetText(label, message);
                label.ForeColor = Color.Green;
            }
            else
            {
                safeSetText(label,e.Error.StackTrace);
                label.ForeColor = Color.Red;
            }
            System.Timers.Timer t = new System.Timers.Timer(3000);
            t.AutoReset = false;
            t.Enabled = true;
            t.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object source, System.Timers.ElapsedEventArgs ee)
            {
                safeSetText(label, "");
                (source as System.Timers.Timer).Dispose();
            });
        }

        public static void DisplayResult(Label label, string message, bool isError)
        {
            if (!isError)
            {
                safeSetText(label, message);
                label.ForeColor = Color.Green;
            }
            else
            {
                safeSetText(label, message);
                label.ForeColor = Color.Red;
            }
            System.Timers.Timer t = new System.Timers.Timer(3000);
            t.AutoReset = false;
            t.Enabled = true;
            t.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object source, System.Timers.ElapsedEventArgs ee)
            {
                safeSetText(label, "");
                (source as System.Timers.Timer).Dispose();
            });
        }

        private static void safeSetText(Label label, string text)
        {
            if (label.InvokeRequired)
            {
                _SafeSetTextCall call = delegate(string s)
                {
                    label.Text = text;
                };

                label.Invoke(call, text);
            }
            else
                label.Text = text;
        }

        private delegate void _SafeSetTextCall(string text);

        public static bool ValidateInputText4Number(string text, bool allowEmpty, out string errorMessage)
        {
            errorMessage = "";
            if (allowEmpty && string.IsNullOrEmpty(text))
                return true;
            bool isValidated = true;
            decimal outResult = 0m;
            isValidated = decimal.TryParse(text, out outResult);
            if (!isValidated)
            {
                errorMessage = "you must input number pattern";
                return false;
            }
            return isValidated;
        }

        public static bool ValidateInputText4Email(string text, bool allowEmpty, out string errorMessage)
        {
            errorMessage = "";
            if (allowEmpty && string.IsNullOrEmpty(text))
                return true;
            bool isValidated = true;
            isValidated = System.Text.RegularExpressions.Regex.IsMatch(text, @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");
            if (!isValidated)
            {
                errorMessage = "you must input email pattern";
                return false;
            }

            return isValidated;
        }

        public static void ExportExcel(DataTable dt)
        {
            if (dt == null) return;

            string saveFileName = "";
            bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "Sheet1";
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消

            Excel.Application xlApp = new Excel.Application();

            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Excel");
                return;
            }

            Excel.Workbooks workbooks = xlApp.Workbooks;
            Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
            Excel.Range range;

            long totalCount = dt.Rows.Count;
            long rowRead = 0;

            //写入字段
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
                range = (Excel.Range)worksheet.Cells[2, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;

            }
            //写入数值
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
                }
                rowRead++;
                Application.DoEvents();
            }

            range = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]);
            range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);

            range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
            range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
            range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;

            if (dt.Columns.Count > 1)
            {
                range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
                range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
                range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
            }

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            if (fileSaved && File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName);

        }
    }
}
